package config

import (
	"context"
	"fileNest/global"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type IndexDefinition struct {
	Collection string
	Indexes    []mongo.IndexModel
}

var indexDefinitions = []IndexDefinition{
	{
		Collection: "entries",
		Indexes: []mongo.IndexModel{
			{
				Keys: bson.D{
					{Key: "user_id", Value: 1},
					{Key: "parent_id", Value: 1},
					{Key: "name", Value: 1},
				},
				Options: options.Index().SetUnique(true),
			},
		},
	},
}

func initIndexes(db *mongo.Database) error {
	for _, def := range indexDefinitions {
		collection := db.Collection(def.Collection)

		_, err := collection.Indexes().CreateMany(context.Background(), def.Indexes)
		if err != nil {
			log.Printf("创建集合 %s 的索引失败: %v", def.Collection, err)
			return err
		}
		log.Printf("集合 %s 的索引创建成功", def.Collection)
	}
	return nil
}

func InitDB() {
	dsn := AppConfig.Database.Dsn
	minPoolSize := AppConfig.Database.MinPoolSize
	maxPoolSize := AppConfig.Database.MaxPoolSize
	clientOptions := options.Client().ApplyURI(dsn).SetMaxPoolSize(maxPoolSize).SetMinPoolSize(minPoolSize)
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatalf("Error connecting to MongoDB, %s", err)
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatalf("❌ MongoDB Ping 失败: %v", err)
	}
	global.DB = client.Database("file_nest")

	if err := initIndexes(global.DB); err != nil {
		log.Fatalf("❌ 初始化索引失败: %v", err)
	}
}
